package com.chen.project.white_jotter.controller;

import com.chen.project.white_jotter.pojo.User;
import com.chen.project.white_jotter.result.Result;
import com.chen.project.white_jotter.service.UserService;
import com.chen.project.white_jotter.utils.JWTUtil;
import com.chen.project.white_jotter.utils.SecurityUtil;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private JWTUtil JWTUtil;

    // 认证成功，返回token
    @RequestMapping("/loginSuccessfully")
    public Result loginSuccessfully(HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        String currentUsername = SecurityUtil.getCurrentUsername();
        String token = null;
        try {
            // 查询数据库
            User user = userService.getUserByUsername(currentUsername);
            //用来存放payload
            Map<String, Object> tokenClaimsMap = new HashMap<>();
            tokenClaimsMap.put("id", user.getId());
            tokenClaimsMap.put("username", user.getUsername());

            token = "Bearer " + JWTUtil.doGenerateToken(tokenClaimsMap, user.getUsername());

            // 返回的数据
            resultMap.put("state", true);
            resultMap.put("msg", "登录成功!");
            resultMap.put("token", token);
        } catch (Exception e) {
            // 认证失败，返回的数据
            e.printStackTrace();
            resultMap.put("state", "false");
            resultMap.put("msg", e.getMessage());
        }
        response.setHeader("Authorization", "Bearer " + token);
        return new Result(200, "登陆成功", resultMap);
    }

    // 登出成功
    @RequestMapping("/logoutSuccessfully")
    public Result toIndex() {
        return new Result(200, "登出成功");
    }

    // 测试是否登陆，不需要返回数据
    @RequestMapping("/test")
    public void test() {
        return;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {

        System.out.println("注册的用户为：" + user);

        String username = user.getUsername();
        String password = user.getPassword();
        username = HtmlUtils.htmlEscape(username);
        user.setUsername(username);

        boolean exist = userService.isExist(username);
        if (exist) {
            String message = "用户名已被使用，请换一个用户名";
            System.out.println(message);
            return new Result(500, message);
        }

        // 生成盐，并对密码进行加密
        String salt = BCrypt.gensalt();
        String encodedPassword = BCrypt.hashpw(user.getPassword(), salt);

        user.setSalt(salt);
        user.setPassword(encodedPassword);
        userService.addUser(user);
        System.out.println("注册用户");
        return new Result(200, "注册用户成功", user);
    }


}
